package com.springboot.demo.design.pattern.listen;

import java.util.ArrayList;
import java.util.List;

/**
 * 监听器持有者（责任链）
 *
 * @author supu
 * @date 2019-07-02 15:40
 **/
public class ListenerHolder<T extends ListenerContext> implements Listener<T> {
    private List<Listener<T>> listeners;


    @Override
    public void listen(T context) {
        try {
            if(listeners == null || listeners.isEmpty() || context == null){
                System.out.println("listeners or context is null");
                return;
            }
            listeners.forEach(listener -> listener.listen(context));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addListener(Listener listener){
        if(listeners == null){
            listeners = new ArrayList<>();
        }
        listeners.add(listener);
    }
}
